package com.study.talk.ui.app.chat

import android.app.Application
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.study.common.DateUtil
import com.study.common.ToastUtil
import com.study.talk.ui.app.base.BaseViewModel
import com.study.talk.data.model.MessageRecord
import com.study.talk.data.model.UserInfo
import com.study.talk.netty.NettyClient
import com.study.talk.netty.message.request.MessageRequest
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import javax.inject.Inject


@HiltViewModel
class ChatViewModel @Inject constructor(
    application: Application
) : BaseViewModel(application) {

    companion object {
        private const val TAG = "ChatViewModel"
    }

    private val _friend = MutableLiveData<UserInfo>()
    val friend: LiveData<UserInfo> get() = _friend

    private val _selectModel = MutableLiveData(false)
    val selectModel : LiveData<Boolean> get() = _selectModel

    private val _analyzeContent = MutableLiveData<String>()
    val analyzeContent : LiveData<String> get() = _analyzeContent

    fun loadFriendInfo(userId: Int) {
        viewModelScope.launch {
            val result = userRepository.getUserInfo(userId)
            if (result == null) {
                ToastUtil.showToast(app, "查询好友信息失败")
            } else {
                result.let { _friend.postValue(it) }
            }
        }
    }

    fun loadMsg(chatId: Int): LiveData<List<MessageRecord>> {
        return msgRepository.getMessages(chatId)
    }

    fun sendImage(path: String) {
        if (path.isEmpty()) {
            Log.e(TAG, "sendImage: path is isEmpty")
            return
        }
        Luban.with(app).load(path).setCompressListener(object : OnCompressListener {
            override fun onStart() {}

            override fun onSuccess(file: File) {
                viewModelScope.launch {
                    val url = fileRepository.upload(file)
                    NettyClient.sendMessage(MessageRequest().apply {
                        receiverId = friend.value?.id
                        content = url
                        messageType = 1
                        dateTime = DateUtil.currentTime()
                    })
                }
            }

            override fun onError(e: Throwable?) {
                ToastUtil.showToast(app, "图片压缩错误")
            }
        }).launch()
    }

    fun changeSelectModel(value : Boolean){
        _selectModel.postValue(value)
    }

    fun notifyAnalyzeContent(content : String){
        _analyzeContent.postValue(content)
    }

}